<?php


namespace App\Http\Controllers;


use App\Models\HelpDoc;
use App\Services\HelpDocService;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;

class HelpDocController extends Controller
{
    public $helpDocService;

    public function __construct(HelpDocService $helpDocService)
    {
        parent::__construct();
        $this->helpDocService = $helpDocService;
    }

    /**
     * 树状标题
     */
    public function getTitleTree()
    {
        $menus = $this->helpDocService->getTitleTree();

        return $this->success($menus);
    }

    /**
     * 新增和编辑
     *
     * @param Request $request
     * @return JsonResponse
     * @author: lxk
     * @date: 2025-03-29 16:18
     */
    public function saveTitle(Request $request) : JsonResponse
    {
        $clickNodeId = $request->input('clickNodeId');
        $title = $request->input('title');
        if (!$this->helpDocService->saveTitle($clickNodeId, $title)) {
            return $this->error('保存失败！');
        }

        return $this->success('', '保存成功');
    }

    /**
     * 保存内容
     */
    public function saveContent(Request $request) : JsonResponse
    {
        $content = $request->input('content');
        $id = HelpDocService::getTitleId($request->input('id'));
        HelpDoc::query()->where('id', $id)->update([
            'content'    => $content,
            'updated_at' => now(),
        ]);

        return $this->success('', '操作成功！');
    }

    /**
     * 获取内容
     */
    public function getContent(Request $request) : JsonResponse
    {
        $id   = HelpDocService::getTitleId($request->input('id'));
        $info = HelpDoc::query()->where('id', $id)->first();
        if ($info) {
            $info->increment('see_count');
        }

        return $this->success($info);
    }

    /**
     * 删除数据
     *
     * @param Request $request
     * @return JsonResponse
     * @author: lxk
     * @date: 2025-03-31 15:34
     */
    public function delNode(Request $request) : JsonResponse
    {
        $clickNodeId = $request->input('clickNodeId');
        $id = substr($clickNodeId, strpos($clickNodeId, '_') + 1);
        if (!HelpDoc::destroy($id)) {
            return $this->success('', '删除失败！');
        }

        return $this->success('', '删除成功！');
    }




}
